<template>
    <div class="h-100 d-flex flex-column" ref="container">
        <div class="position-relative zone_select">
            <input readonly type="text" ref="zoneSelect" data-toggle="city-picker" data-responsive="true" class="w-100">
        </div>
        <div id="container" class="w-100 h-100 mt-2"></div> 

        <el-dialog title="光交箱详情" :visible.sync="dialogBoxDetail" top="5vh" width="1000px">
			<OpticalBoxDetail :data="selectedBox"></OpticalBoxDetail>
		</el-dialog>
    </div>
</template>

<script>

// http://www.jq22.com/jquery-info14757
// http://tshi0912.github.io/city-picker/
import {mapState} from 'vuex';
import OpticalBoxDetail from './dialog/OpticalBoxDetail.dialog';

export default {
    name: 'OpticalBoxMap',
    components: {
		OpticalBoxDetail
	},
    data(){
        return {
            loading: null,
            cityMarkerArray: [],
            dialogBoxDetail: false,
            selectedBox: {}
        }
    },
    computed: {
        ...mapState({
            userInfo: 'userInfo'
        })
    },
    methods: {
        setCityLabel(map, item){
            var point = new BMap.Point(item.longitude, item.latitude);
            var marker = new BMap.Marker(point);  // 创建标注
            map.addOverlay(marker);              // 将标注添加到地图中

            var label = new BMap.Label(item.count,{offset:new BMap.Size(0,0)});
            label.setStyle({
                border: 'none',
                background: 'rgba(0,0,0,0)',
                color: '#fff',
                width: '20px',
                textAlign: 'center',
                lineHeight: '1.5'
            });
            marker.setLabel(label);
            return marker;
        },
        // 抓取某个省中所有的城市
        fetchCityList(map, city){
            if (this.loading) this.loading.close();
            this.loading = this.$loading({
                fullscreen: true,
                lock: true,
                target: this.$refs.container
            });
                
            let url = this.$obHttp.Api.getLockCount,
                bussinessCode = this.userInfo.businessCode;

            this.$obHttp.httpGet(`${url}${bussinessCode}`, {
                prov: city
            }).then(response => {
                this.loading.close();
                this.loading = null;
                if( response ){
                    let { data: list } = response;
                    Array.isArray(list) && list.forEach((value, index)=>{
                        let marker = this.setCityLabel(map, value);
                        this.cityMarkerArray.push(marker);
                    });
                }
            });
        },
        // 抓取详细的数据
        fetchBoxList(map, address){
            this.$obHttp.httpPost(this.$obHttp.Api.getLockList, {
                "merNo": this.userInfo.businessCode, // bussinessCode
                "numPerPage": 1000, //
                "pageNum": 0, //
                "position": address,
            }).then(response => {
                if( response ){
                    let {contents, totalElements, totalPages} = response.data;
                    this.cityMarkerArray.forEach(item=>map.removeOverlay(item));
                    Array.isArray(contents) && contents.forEach(item=>{
                        var point = new BMap.Point(item.longitude, item.latitude);
                        var marker = new BMap.Marker(point);  // 创建标注
                        map.addOverlay(marker);   

                        marker.addEventListener('click', (e)=>{
                            this.selectedBox = item;
                            this.dialogBoxDetail = true;
                        });
                    });
                }
            });
        },
        getBoundary(map, city){
            return new Promise((resolve, reject)=>{
                var bdary = new BMap.Boundary();
                bdary.get(city, rs=>{       //获取行政区域
                    this.cityMarkerArray = [];
                    map.clearOverlays();        //清除地图覆盖物       
                    var count = rs.boundaries.length; //行政区域的点有多少个
                    if (count === 0) {
                        alert('未能获取当前输入行政区域');
                        return resolve(false);
                    }
                    var pointArray = [];
                    for (var i = 0; i < count; i++) {
                        var ply = new BMap.Polygon(rs.boundaries[i], {strokeWeight: 2, strokeColor: "#ff0000"}); //建立多边形覆盖物
                        map.addOverlay(ply);  //添加覆盖物
                        pointArray = pointArray.concat(ply.getPath());
                    }    
                    map.setViewport(pointArray);    //调整视野      
                    resolve(true);         
                }); 
            });
        }
    },
    mounted() {
        $(this.$refs.zoneSelect).citypicker();

        var map = new BMap.Map("container"); 
        map.centerAndZoom("广东省深圳市",10);

        map.enableScrollWheelZoom();
        // map.disableScrollWheelZoom();
        map.enableInertialDragging();
        map.enableContinuousZoom();

        var top_left_control = new BMap.ScaleControl({anchor: BMAP_ANCHOR_TOP_LEFT});// 左上角，添加比例尺
        var top_left_navigation = new BMap.NavigationControl();  //左上角，添加默认缩放平移控件
        //右上角，仅包含平移和缩放按钮
        // var top_right_navigation = new BMap.NavigationControl({
        //     anchor: BMAP_ANCHOR_TOP_RIGHT, 
        //     type: BMAP_NAVIGATION_CONTROL_SMALL
        // }); 

        map.addControl(top_left_control);
        map.addControl(top_left_navigation);
        // map.addControl(top_right_navigation);

        // map.addEventListener('zoomend', ()=>{
        //     let zoom = map.getZoom();
        // });
        
        let $input = $(this.$refs.zoneSelect);
        let citypicker = $input.data('citypicker');
        let timer = setInterval(()=>{
            citypicker = $input.data('citypicker');
            if( citypicker ) {
                clearInterval(timer);
                $input.on('cp:updated', ()=>{
                    let val = $input.val().split('/').join('');
                    // 防止地图在渲染城市的时候清空
                    this.getBoundary(map, val).then(result=>{
                        let codeLength = citypicker.getCode().split('/').length;
                        if( codeLength === 1 ){
                            this.fetchCityList(map, citypicker.getVal());
                            citypicker.close();
                        } else {
                            this.fetchBoxList(map, citypicker.getVal());
                        }
                    });
                });
            }
        }, 100);

    },
    beforeDestroy(){
        $(this.$refs.zoneSelect).remove();
        this.loading = null;
        this.cityMarkerArray = [];
    }
}
</script>

<style lang="scss" scoped>
    #container{
        flex: 1;
    }
    .zone_select{
        width: 240px;
    }
</style>

